import { defineStore } from 'pinia'
import { ref } from 'vue'

import type { SignData } from '@/apis/model/auth'
import type { UserModel } from '@/apis/model/user'
import { jumpNameAfterLogin, jumpNameAfterSignOut, storesKey } from '@/config'
import router from '@/router'
import i18n from '@/locales'
import { storage } from '@/utils/sessionStorage'
// import { useRouter } from 'vue-router'

export const useAppStore = defineStore(
  storesKey.app,
  () => {
    const isLogined = ref(true)
    // const router = useRouter()
    const token = ref<string | undefined>()
    const userInfo = ref<Partial<UserModel>>()
    // console.log('localStorage.get() : ', localStorage.get('lang'))
    type Locale = 'zh' | 'en'
    console.log('storage.get(lang): ', storage.get('lang'))
    const locale = ref<Locale>(storage.get('lang') || 'zh')
    /**
     * 登录
     * @param data 登录参数
     * @returns Promise<boolean>
     */
    const signInAction = (data: SignData): Promise<boolean> => {
      return new Promise((resolve, reject) => {
        // setTimeout 模拟接口请求间隔
        signInApi(data)
          .then(res => {
            isLogined.value = true
            userInfo.value = res.admin
            token.value = res.token
            router.replace({ name: jumpNameAfterLogin })
            resolve(true)
          })
          .catch(e => {
            console.error(e)
            reject(false)
          })
      })
    }
    /**
     * 登出
     * @returns Promise<boolean>
     */
    const signOutAction = (): Promise<boolean> => {
      // return new Promise((resolve, reject) => {
      return new Promise(() => {
        // signOutApi()
        //   .then((res) => {
        //     isLogined.value = true
        //     userInfo.value = res.userInfo
        //     token.value = res.token
        //     router.replace({ name: jumpNameAfterLogin })
        //     resolve(true)
        //   })
        //   .catch((e) => {
        //     console.error(e)
        //     reject(false)
        //   })
        // setTimeout 模拟接口请求间隔
        isLogined.value = false
        userInfo.value = undefined
        token.value = undefined
        locale.value = 'zh'
        storage.set('lang', 'zh')
        i18n.global.locale.value = 'zh'
        router.replace({ name: jumpNameAfterSignOut })
      })
    }
    const SET_LOCALE = (lang: Locale) => {
      //语言切换
      locale.value = lang
      storage.set('lang', lang)
      i18n.global.locale.value = lang
    }
    const clearStatus = () => {
      locale.value = 'zh'
      storage.set('lang', 'zh')
      i18n.global.locale.value = 'zh'
    }
    return {
      isLogined,
      token,
      locale,
      userInfo,
      signInAction,
      signOutAction,
      SET_LOCALE
    }
  },
  { persist: { storage: sessionStorage } }
)
